<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span v-if="dictType">字典数据 - {{ dictName }}</span>
          <span v-else>字典数据</span>
          <div class="right-actions" v-if="dictType">
            <el-button type="primary" size="small" @click="goBack">返回字典类型</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="字典类型" prop="dictType">
          <el-select v-model="queryParams.dictType" placeholder="请选择字典类型" clearable style="width: 240px" @change="handleDictTypeChange">
            <el-option v-for="dict in dictTypeOptions" :key="dict.type" :label="`${dict.name}(${dict.type})`" :value="dict.type" />
          </el-select>
        </el-form-item>
        <el-form-item label="字典标签" prop="label">
          <el-input v-model="queryParams.label" placeholder="请输入字典标签" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="数据状态" clearable style="width: 240px">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb-3">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd" :disabled="!queryParams.dictType">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" :icon="Delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" :icon="Download" @click="handleExport" :disabled="!queryParams.dictType">导出</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" row-key="id">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="字典编码" prop="id" width="80" />
        <el-table-column label="字典标签" prop="label">
          <template #default="scope">
            <span :class="scope.row.cssClass || ''">{{ scope.row.label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="字典值" prop="value" />
        <el-table-column label="字典类型" prop="dictType" :show-overflow-tooltip="true" />
        <el-table-column label="排序" prop="sort" width="80" />
        <el-table-column label="列表样式" prop="listClass" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.listClass" :type="scope.row.listClass">{{ scope.row.listClass }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scope">
            <dict-tag dict-type="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="dataFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字典类型" prop="dictType">
          <el-select v-model="form.dictType" placeholder="请选择字典类型" style="width: 100%" :disabled="form.id !== undefined">
            <el-option v-for="dict in dictTypeOptions" :key="dict.type" :label="`${dict.name}(${dict.type})`" :value="dict.type" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据标签" prop="label">
          <el-input v-model="form.label" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据值" prop="value">
          <el-input v-model="form.value" placeholder="请输入数据值" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <dict-radio
            v-model="form.status"
            dict-type="sys_normal_disable"
          />
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="form.cssClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="列表样式" prop="listClass">
          <el-select v-model="form.listClass" placeholder="请选择显示样式">
            <el-option label="默认" value="" />
            <el-option label="主要(primary)" value="primary" />
            <el-option label="成功(success)" value="success" />
            <el-option label="信息(info)" value="info" />
            <el-option label="警告(warning)" value="warning" />
            <el-option label="危险(danger)" value="danger" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete, Edit, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import {
  getDictTypeList,
  getDictDataList,
  getDictDataDetail,
  createDictData,
  updateDictData,
  deleteDictData,
  exportDictData,
  getAllDictTypes
} from '@/api/dict'
import Pagination from '@/components/Pagination/index.vue'
import useDict from '@/hooks/useDict'

const router = useRouter()
const route = useRoute()

// 状态数据字典
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 0, label: '禁用' }
]

// 字典类型
const dictType = ref('')
const dictName = ref('')
const dictTypeOptions = ref([])

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  dictType: '',
  label: '',
  status: undefined
})

// 表格数据
const dataList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedIds = ref([])
const queryFormRef = ref(null)
const dataFormRef = ref(null)

// 表单参数
const form = reactive({
  dictType: '',
  label: '',
  value: '',
  sort: 0,
  status: 1,
  cssClass: '',
  listClass: '',
  remark: ''
})

// 表单验证规则
const rules = {
  dictType: [
    { required: true, message: '字典类型不能为空', trigger: 'change' }
  ],
  label: [
    { required: true, message: '数据标签不能为空', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '数据值不能为空', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '排序不能为空', trigger: 'blur' }
  ]
}

// 弹窗对象
const dialog = reactive({
  title: '',
  visible: false
})

// 字典数据
const { dicts } = useDict('sys_normal_disable')

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return ''
  return new Date(value).toLocaleString()
}

// 初始化字典类型选项
const initDictTypeOptions = async () => {
  try {
    const res = await getAllDictTypes()
    dictTypeOptions.value = res.data || []
    
    // 如果路由参数中有字典类型，则选中该类型
    if (route.query.dictType) {
      queryParams.dictType = route.query.dictType
      dictType.value = route.query.dictType
      
      // 查找字典名称
      const typeInfo = dictTypeOptions.value.find(item => item.type === dictType.value)
      if (typeInfo) {
        dictName.value = typeInfo.name
      }
      
      // 获取字典数据列表
      getList()
    }
  } catch (error) {
    console.error('获取字典类型选项失败:', error)
  }
}

// 获取字典数据列表
const getList = async () => {
  if (!queryParams.dictType) return
  
  loading.value = true
  try {
    const res = await getDictDataList(queryParams)
    dataList.value = res.data.list || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('获取字典数据列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 字典类型变更
const handleDictTypeChange = (value) => {
  if (value) {
    dictType.value = value
    
    // 查找字典名称
    const typeInfo = dictTypeOptions.value.find(item => item.type === value)
    if (typeInfo) {
      dictName.value = typeInfo.name
    }
  } else {
    dictType.value = ''
    dictName.value = ''
  }
  
  // 重置表格数据
  dataList.value = []
  total.value = 0
  
  // 获取字典数据列表
  if (value) {
    getList()
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  
  // 如果路由参数中有字典类型，则不清除字典类型
  if (route.query.dictType) {
    queryParams.dictType = route.query.dictType
  }
  
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.title = '添加字典数据'
  dialog.visible = true
  
  // 设置当前选中的字典类型
  if (queryParams.dictType) {
    form.dictType = queryParams.dictType
  }
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  dialog.title = '修改字典数据'
  dialog.visible = true
  loading.value = true
  
  try {
    const res = await getDictDataDetail(row.id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取字典数据详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 表单重置
const resetForm = () => {
  dataFormRef.value?.resetFields()
  Object.assign(form, {
    dictType: queryParams.dictType || '',
    label: '',
    value: '',
    sort: 0,
    status: 1,
    cssClass: '',
    listClass: '',
    remark: ''
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除字典数据"${row.label}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDictData(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 批量删除操作
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  const dictLabels = dataList.value
    .filter(item => selectedIds.value.includes(item.id))
    .map(item => item.label)
    .join('、')
  
  ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}条字典数据(${dictLabels})吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await Promise.all(selectedIds.value.map(id => deleteDictData(id)))
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  dataFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (form.id) {
          await updateDictData(form.id, form)
          ElMessage.success('修改成功')
        } else {
          await createDictData(form)
          ElMessage.success('添加成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 导出字典数据
const handleExport = async () => {
  try {
    const params = {
      dictType: queryParams.dictType,
      label: queryParams.label,
      status: queryParams.status
    }
    
    const res = await exportDictData(params)
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `字典数据_${queryParams.dictType}.xlsx`
    link.click()
    URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 返回字典类型列表
const goBack = () => {
  router.push('/system/dict/type')
}

onMounted(() => {
  initDictTypeOptions()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .right-actions {
    display: flex;
    gap: 10px;
  }
}

.search-form {
  margin-bottom: 20px;
}

.mb-3 {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 